﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using log4net;
using Newtonsoft.Json;

namespace LeakView.common
{
    public class Ajax : IDisposable
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Ajax));

        private HttpClient httpClient;
        public HttpClient HttpCLient { get => httpClient; }
        public TimeSpan Timeout { get => httpClient.Timeout; set => httpClient.Timeout = value; }

        public Ajax()
        {
            Initialize();
            
        }

        private void Initialize()
        {
            httpClient = new HttpClient
            {
                MaxResponseContentBufferSize = 64000000,
                Timeout = TimeSpan.FromSeconds(5)
            };
        
            httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");

        }

        public T DoPost<T>(AjaxContent content)
        {
            return DoPost<T>(content, default(T));
        }

        private T DoPost<T>(string url, HttpContent content)
        {
            string text = "";
            var task = this.httpClient.PostAsync(url, content);
            HttpResponseMessage response = task.Result.EnsureSuccessStatusCode();
            var result = response.Content.ReadAsStringAsync();
            text = result.Result;
            return JsonConvert.DeserializeObject<T>(text);
        }

        private T DoPost<T>(AjaxContent content, T defaultValue)
        {
            try
            {
                return DoPost<T>(content.Url, content.Content);
            }
            catch
            {
                return defaultValue;
            }
        }

        public void Dispose()
        {
            if (httpClient != null)
            {
                httpClient.Dispose();
                httpClient = null;
            }
        }

        public static string MakeUrl(string home, string path)
        {
            string url = home;
            if (!url.EndsWith("/"))
                url += "/";
            if (path.StartsWith("/"))
            {
                url += path.Skip(1);
            }
            else
            {
                url += path;
            }
            return url;
        }
    }

    public class AjaxContent
    {
        private string url;
        public string Url { get => url;}
        
        private List<KeyValuePair<String, String>> parameters = new List<KeyValuePair<string, string>>();

        public static AjaxContent Get()
        {
            return new AjaxContent();
        }

        public AjaxContent setUrl(string url)
        {
            this.url = url;
            return this;
        }

        public AjaxContent setUrl(string home, string path)
        {
            return setUrl(Ajax.MakeUrl(home, path));
        }

        public AjaxContent AddParameter(string key, string value)
        {
            if (key == null || key.Length == 0) return this;

            if (value == null || value.Length == 0) return this;

            parameters.Add(new KeyValuePair<string, string>(key, value));
            return this;
        }

        public AjaxContent clearParameters()
        {
            parameters.Clear();
            return this;
        }

        public FormUrlEncodedContent Content
        {
            get => parameters.Count == 0 ? null : new FormUrlEncodedContent(parameters);
        }


    }

}
